package Servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLStreamException;

import org.apache.solr.client.solrj.SolrServerException;

import DataObjects.Article;
import DataObjects.Topic;
import DisplayDatas.FullTopicToDisplay;
import DisplayDatas.SearchResultToDisplay;
import DisplayDatas.TopicToDisplay;
import Main.GeneralFunctions;
import Main.Pair;
import SolR.MySolR;
import XMLCreator.XMLCreateAnswer;
import XMLCreator.XMLCreatorTopicAnswer;

public class SearchResultServlet extends SuperServlet{

	private static final long serialVersionUID = 1L;

	private MySolR solR;
	private HashMap<Integer,Topic> allTopics;
	
	public SearchResultServlet(MySolR solR,HashMap<Integer,Topic> allTopics){
		this.solR=solR;
		this.allTopics=allTopics;
	}

//	private HashMap<Integer, TopicToDisplay> getArticleList(String query) throws SolrServerException{
//		HashMap<Integer, TopicToDisplay> ans=new HashMap<Integer, TopicToDisplay>();
//		solR.queryTopics(query);
//		
//		for(Article article : articles){
//			allArticles.add(article);
//		}
//	}
	
	protected FullTopicToDisplay searchTopicResult(String query,int page,Vector<Integer> givenTopics) throws SolrServerException{//TODO same how (SearchResultServlet)
		Pair<Long,LinkedList<Article>> allArticles=solR.query(query, page);
		HashMap<Integer, TopicToDisplay> topics=solR.queryTopics(query);
		Vector<Pair<String, Integer>> cats=solR.queryCats(query);
		
		for(int topicId : givenTopics){
			topics.put(topicId, new TopicToDisplay(allTopics.get(topicId)));
		}
		
		Vector<TopicToDisplay> allTopics=new Vector<TopicToDisplay>();
		for(int id : givenTopics){
			if (topics.get(id)==null){//TODO
				System.out.println(topics);
			}
			allTopics.add(topics.get(id));
		}
		
		FullTopicToDisplay ans=new FullTopicToDisplay(allArticles.getSecend(),query,allArticles.getFirst(),allTopics,topics.values(),cats);//TODO not all is roots (SearchResultServlet)
		return ans;
	}
	
	private SearchResultToDisplay searchResult(String query,int page) throws SolrServerException{//TODO same how (SearchResultServlet)
		
		Pair<Long,LinkedList<Article>> allArticles=solR.query(query, page);
		HashMap<Integer, TopicToDisplay> topics=solR.queryTopics(query);
		Vector<Pair<String, Integer>> cats=solR.queryCats(query);
		SearchResultToDisplay ans=new SearchResultToDisplay(allArticles.getSecend(),query,allArticles.getFirst(),topics.values(),cats);//TODO not all is roots (SearchResultServlet)
		
		return ans;
	}

	protected void buildResponse(HttpServletRequest request, HttpServletResponse response)  throws IOException
	{
		
		
		
		int page=fieldToInt(request,"page");
		String query=request.getParameter("query");
		
		
		if (request.getParameter("query")==null)
			query="*:*";
		else{
			query=GeneralFunctions.convertPlus(query);
		}
		
		System.out.println("servletresult:buildResponse "+query);//TODO
		
//		query=GeneralFunctions.convertPlus(query);
		
		String topic=request.getParameter("topic");

		try {
//			System.out.println("servletresult:  1 ");//TODO
//			System.out.println("servletresult:  21 "+topic+" "+query);//TODO
			if (topic==null || topic.equals("-1")){
//				System.out.println("servletresult:  3 "+response);//TODO
				SearchResultToDisplay ans=searchResult(query,page);
//				System.out.println(ans.getArticles().iterator().next().getTopics().iterator().next().getName()+" "+ans.getRoots());//TODO
				
				
				OutputStream out2=response.getOutputStream();
				PrintWriter out = new PrintWriter(new OutputStreamWriter(out2, "UTF8") ,true);
				
//				PrintWriter out=response.getWriter();
				
				
//				System.out.println("servletresult:  33 ");//TODO
				new XMLCreateAnswer().build(ans,out);
//				new XML1().build(null,out);
//				System.out.println("servletresult:  34 ");//TODO
				out.close();
			}
			else{
//				System.out.println("servletresult:  2 ");//TODO
				String[] splited=topic.split(",");
				Vector<Integer> allTopics=new Vector<Integer>();
//				System.out.println("servletresult:  4 "+splited.length);//TODO
				for(int i=0;i<splited.length;i++){
//					System.out.println("servletresult:  "+splited[i]);//TODO
					allTopics.add(Integer.parseInt(splited[i]));
				}
//				System.out.println("servletresult:  5 ");//TODO
				
				FullTopicToDisplay ans=searchTopicResult(query,page,allTopics);
				PrintWriter out=response.getWriter();
//				new XML2().build(null,out);
				new XMLCreatorTopicAnswer().build(ans,out);
				out.close();
				
//				out=new PrintWriter(new File("a1.txt"));//TODO
//				
//				new XMLCreatorTopicAnswer().build(ans,out);
//				out.close();
			}
		} catch (XMLStreamException e) {
			System.out.println("Error 4 SearchResultServlet");//TODO error 4 (SearchResultServlet)
		} catch (FactoryConfigurationError e) {
			System.out.println("Error 5 SearchResultServlet");//TODO error 5 (SearchResultServlet)
		} catch (SolrServerException e) {
			System.out.println("Error 51 SearchResultServlet "+query);//TODO error 51 (SearchResultServlet)
			System.out.println(e.getMessage());
			System.out.println(e);
		} catch (RuntimeException e) {
			
			System.out.println("Error 59 SearchResultServlet");//TODO error 59 (SearchResultServlet)
			System.out.println(e);
			e.printStackTrace();
		}	

	}

}